import api from '../api'
import {
  INIT_HISTORY,
  ADD_HISTORY,
  CLEAR_HISTORY,
  GOT_SEARCH_RESULTS,
  CLEAR_SEARCH_RESULTS
} from './bookSearchMutations'
import {
  GET_SEARCH_RESULTS
} from './bookSearchActions'
const bookSearch = {
  namespaced: true,
  state: {
    history: [],
    searchResults: null
  },
  mutations: {
    [INIT_HISTORY] (state) {
      !localStorage.getItem('bookSearchHistory')
        ? localStorage.setItem('bookSearchHistory', '[]')
        : state.history = JSON.parse(localStorage.getItem('bookSearchHistory'))
    },
    [ADD_HISTORY] (state, item) {
      if (item) {
        if (state.history.length === 0) {
          state.history.unshift(item)
          localStorage.setItem('bookSearchHistory', JSON.stringify(state.history))
        } else {
          for (let i = 0; i < state.history.length; i++) {
            if (state.history[i] === item) {
              return false
            }
          }
          state.history.unshift(item)
          localStorage.setItem('bookSearchHistory', JSON.stringify(state.history))
        }
      }
    },
    [CLEAR_HISTORY] (state) {
      if (state.history.length !== 0) {
        state.history = []
        localStorage.setItem('bookSearchHistory', JSON.stringify(state.history))
      }
    },
    [GOT_SEARCH_RESULTS] (state, data) {
      state.searchResults = data
    },
    [CLEAR_SEARCH_RESULTS] (state) {
      if (state.searchResults !== null && state.searchResults.length !== 0) {
        state.searchResults = null
      }
    }
  },
  actions: {
    [GET_SEARCH_RESULTS] ({ commit }, value) {
      if (value) {
        api.getSearchResults(value).then(data => {
          commit('gotSearchResults', data)
          if (data.length !== 0) {
            commit('addHistory', value)
          }
        }).catch(err => {
          console.err(err)
        })
      }
    }
  },
  getters: {}
}

export default bookSearch
